package com.util;

import java.math.BigDecimal;

public class MoneyUtils {
	
	/**
	 * 人民币符号的3位空格分割表示：￥123 456 789.56
	 * @param cent 已分为单位的钱数
	 * @return
	 */
	public static String getMoneySpaceSplitCNY(long cent){
		return "￥"+getMoneySpaceSplit(cent);
	}
	/**
	 * 人民币符号的3位逗号分割表示：￥123,456,789.56
	 * @param cent 已分为单位的钱数
	 * @return
	 */
	public static String getISOMoneyCNY(long cent){
		return "￥"+getISOMoney(cent);
	}
	public static String getISOMoneyCNY(BigDecimal yuan){
		return "￥"+getISOMoney(yuan);
	}
	/**
	 * 大美元符号的3位逗号分割表示：＄123,456,789.56
	 * @param cent
	 * @return
	 */
	public static String getISOMoneyUSD(long cent){
		return "＄"+getISOMoney(cent);
	}
	public static String getISOMoneyUSD(BigDecimal yuan){
		return "＄"+getISOMoney(yuan);
	}
	/**
	 * 小美元符号的3位逗号分割表示：$123,456,789.56
	 * @param cent
	 * @return
	 */
	public static String getISOMoneyUsd(long cent){
		return "$"+getISOMoney(cent);
	}
	public static String getISOMoneyUsd(BigDecimal yuan){
		return "$"+getISOMoney(yuan);
	}
	/**
	 * ３位逗号分隔
	 * @param cent　like '123000'
	 * @return like '1,230.00'
	 */
	public static String getISOMoney(long cent){
		return getMoneyString(cent,3,",");
	}
	public static String getISOMoney(BigDecimal yuan){
		checkBigDecimal2LongValue(yuan);
		long cent = yuan.movePointRight(2).longValue();
		return getMoneyString(cent,3,",");
	}
	/**
	 * ３位空格分隔
	 * @param cent　
	 * @return
	 */
	public static String getMoneySpaceSplit(long cent){
		return getMoneyString(cent,3," ");
	}
	public static String getMoneySpaceSplit(BigDecimal yuan){
		checkBigDecimal2LongValue(yuan);
		long cent = yuan.movePointRight(2).longValue();
		return getMoneyString(cent,3," ");
	}
	private static boolean checkBigDecimal2LongValue(BigDecimal d){
		if(d.compareTo(new BigDecimal("92233720368547758.07"))>0){
			System.out.println("超过Java中long类型的最大表示值!结果可能不正确!");
			return false;
		}
		return true;
	}
	///////////////////////////////////
	private static String getMoneyString(long cent,int splitNum,String split){
		boolean f = false;
		if(cent<0){
			cent = cent*-1;
			f = true;
		}
		String money = String.valueOf(cent);
		if(cent<10){
			money = "00" + money;
		}else if(cent<100){
			money = "0" + money;
		}
		String yuan = money.substring(0,money.length()-2);
		String fen  = money.substring(money.length()-2);
		char[] x = yuan.toCharArray();
		StringBuffer sb = new 	StringBuffer();
		int yu = (x.length%splitNum)-1;
		if(yu<0)yu += splitNum;
		for(int i=x.length-1 ; i>=0 ; i--){
			if(i!=x.length-1 && i%splitNum==yu)sb.insert(0,split);
			sb.insert(0, x[i]);
		}
		sb.append(".");
		sb.append(fen);
		money = sb.toString();
		if(f)money = "-"+money;
		return money;
	}
	
	public static void main(String[] args){
		System.out.println(getISOMoney(new BigDecimal("92233720368547758.0699")));
	}
}
